<template>
  <view class="flex flex-col h-100vh bg-#f5f5f5">
    <!-- <navigator
      url="/pages/test/index"
      open-type="navigate"
      hover-class="navigator-hover"
    > -->
    <!-- 雷达扫描图 -->
    <view class="flex justify-center mt-60rpx mb-60rpx">
      <image src="../../static/search.gif" class="w-200rpx h-200rpx" mode="scaleToFill" />
    </view>
    <!-- </navigator> -->

    <!-- 设备列表标题 -->
    <view class="flex justify-between items-center px-40rpx mb-30rpx">
      <view class="flex items-center">
        <view class="w-10rpx h-40rpx bg-black mr-20rpx"></view>
        <text class="text-34rpx font-medium">发现设备: {{ deviceList.length }}</text>
      </view>
      <view class="flex items-center" @click="refreshDevices">
        <text class="i-carbon-renew text-36rpx mr-10rpx"></text>
        <text class="text-30rpx text-gray-500">刷新</text>
      </view>
    </view>

    <!-- 设备列表 -->
    <view class="px-30rpx">
      <view v-for="(device, index) in deviceList" :key="index"
        class="flex justify-between items-center p-40rpx mb-20rpx bg-white rounded-20rpx border border-gray-100">
        <text class="text-32rpx text-gray-700">{{ device.name }}</text>
        <!-- <text class="text-32rpx text-gray-700">{{ device.advertisServiceUUIDs }}</text> -->
        <view class="bg-blue-500 text-white text-28rpx px-40rpx leading-60rpx rounded-full" @click="connect(device)">
          连接
        </view>
      </view>
    </view>

    <!-- 底部指示条 -->
    <view class="mt-auto mb-10rpx flex justify-center">
      <view class="w-200rpx h-10rpx bg-black rounded-full"></view>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { onReady, onUnload, onLoad, onShow } from "@dcloudio/uni-app";
// 设备列表
const deviceList = ref([]); // 移除模拟数据
const services = ref([]);
const deviceId = ref("");
const serviceId = ref("");
const characteristicId = ref("");
const name = ref("");
const advertisServiceUUIDs = ref([]);

const initBlue = async () => {
  return new Promise((resolve, reject) => {
    uni.openBluetoothAdapter({
      success(res) {
        console.log("初始化蓝牙成功");
        console.log("initBlue", res);
        resolve(res); // 成功后返回结果
      },
      fail(err) {
        console.log("初始化蓝牙失败");

        if (err.errCode == '10001') {
          uni.showModal({
            title: '蓝牙未打开',
            content: '请先打开手机蓝牙',
            showCancel: false,
            success: ({ confirm, cancel }) => { }
          })
        }

        console.error(err);
        reject(err); // 失败后返回错误
      },
    });
  });
};

const discovery = async () => {
  return new Promise((resolve, reject) => {
    uni.startBluetoothDevicesDiscovery({
      success(res) {
        console.log("开始搜索");
        // 开启监听回调
        uni.onBluetoothDeviceFound(found);
        resolve(res); // 成功后返回结果
      },
      fail(err) {
        console.log("搜索失败");
        console.error(err);
        reject(err); // 失败后返回错误
      },
    });
  });
};

const found = (res) => {
  console.log(res);
  if (res.devices[0].name) {
    deviceList.value.push(res.devices[0]);
  }
};

const connect = (data) => {
  uni.showLoading({
    title: "连接中",
    mask: true,
  });
  console.log("data", data);

  name.value = data.name; // 将获取到的设备名称存起来
  deviceId.value = data.deviceId; // 将获取到的设备ID存起来
  advertisServiceUUIDs.value = data.advertisServiceUUIDs;

  uni.createBLEConnection({
    deviceId: data.deviceId,
    success(res) {
      console.log("连接成功");
      console.log("createBLEConnection:", res);
      setTimeout(() => {
        getServices(); // 获取服务
      }, 1000);
      // 停止搜索
      stopDiscovery();
    },
    fail(err) {
      console.error("连接失败", err);
    },
  });
};

const stopDiscovery = () => {
  uni.stopBluetoothDevicesDiscovery({
    success(res) {
      console.log("停止成功");
      console.log(res);
    },
    fail(err) {
      console.log("停止失败");
      console.error(err);
    },
  });
};

const getServices = () => {
  // 如果是自动链接的话，uni.getBLEDeviceServices方法建议使用setTimeout延迟1秒后再执行
  uni.getBLEDeviceServices({
    deviceId: deviceId.value,
    success(res) {
      console.log("getBLEDeviceServices", res); // 可以在res里判断有没有硬件佬给你的服务
      console.log("services", res.services); // 可以在res里判断有没有硬件佬给你的服务

      services.value = res.services;

      // 把所有的services存起来
      if (res.services.length > 0) {
        serviceId.value = res.services[0].uuid; // 存储服务信息
        setTimeout(() => {
          getCharacteristics(res.services[0]); // 获取特征值
        }, 1000);
        // services.value.forEach(async (service) => {
        //   let charList = await getCharacteristics(service); // 获取特征值
        //   service.charList = charList;
        // });
      } else {
        console.log("获取服务失败 长度为0");
      }
    },
    fail(err) {
      console.error("获取服务失败:", err);
      uni.hideLoading();
    },
  });
};

async function getCharacteristics(service) {
  uni.getBLEDeviceCharacteristics({
    deviceId: deviceId.value,
    serviceId: service.uuid,
    success(res) {
      console.log("getBLEDeviceCharacteristics", res.characteristics); // 可以在此判断特征值是否支持读写等操作，特征值其实也需要提前向硬件佬索取的

      if (res.characteristics.length === 0) {
        console.log("获取特征值失败 长度为0");
        return;
      }
      console.log("res.characteristics[0]", res.characteristics[0]);
      characteristicId.value = res.characteristics[5].uuid; // 存储特征值信息
      // 写入成功
      uni.hideLoading();
      uni.navigateBack();

      console.log("characteristicId", characteristicId.value);

      if (!characteristicId.value) {
        console.log("获取特征值失败 不可写入");
        return;
      }
    },
    fail(err) {
      uni.hideLoading();
      console.error("获取特征值失败", err);
      reject([]);
    },
  });

  // return new Promise((resolve, reject) => {
  //   setTimeout(() => {
  //     uni.getBLEDeviceCharacteristics({
  //       deviceId: deviceId.value,
  //       serviceId: service.uuid,
  //       success(res) {
  //         console.log("getBLEDeviceCharacteristics", res.characteristics); // 可以在此判断特征值是否支持读写等操作，特征值其实也需要提前向硬件佬索取的
  //         resolve(res.characteristics);

  //         // if (res.characteristics.length === 0) {
  //         //   console.log("获取特征值失败 长度为0");
  //         //   return;
  //         // }
  //         // console.log("res.characteristics[0]", res.characteristics[0]);
  //         // // characteristicId.value = res.characteristics[5].uuid; // 存储特征值信息
  //         // characteristicId.value = res.characteristics[0].uuid; // 存储特征值信息

  //         // console.log("characteristicId", characteristicId.value);

  //         // if (!characteristicId.value) {
  //         //   console.log("获取特征值失败 不可写入");
  //         //   return;
  //         // }
  //       },
  //       fail(err) {
  //         console.error("获取特征值失败", err);
  //         reject([]);
  //       },
  //     });
  //   }, 1000);
  // });
}

onLoad(() => {
  deviceId.value = uni.getStorageSync("deviceId") || "";
  serviceId.value = uni.getStorageSync("serviceId") || "";
  characteristicId.value = uni.getStorageSync("characteristicId") || "";
  name.value = uni.getStorageSync("name") || "";
  advertisServiceUUIDs.value = uni.getStorageSync("advertisServiceUUIDs") || [];
});

onReady(async () => {
  await initBlue(); // 初始化蓝牙
  await discovery(); // 开始搜索
});

onUnload(() => {
  // 保存信息到storage
  uni.setStorageSync("deviceId", deviceId.value);
  uni.setStorageSync("serviceId", serviceId.value);
  uni.setStorageSync("characteristicId", characteristicId.value);
  uni.setStorageSync("name", name.value);
  uni.setStorageSync("advertisServiceUUIDs", advertisServiceUUIDs.value);

  uni.setStorageSync("services", services.value);

  stopDiscovery(); // 页面卸载时停止搜索
});
</script>

<style>
.flex {
  display: flex;
}

.flex-col {
  flex-direction: column;
}

.h-100vh {
  height: 100vh;
}

.bg-#f5f5f5 {
  background-color: #f5f5f5;
}

.justify-center {
  justify-content: center;
}

.mt-60rpx {
  margin-top: 60rpx;
}

.mb-60rpx {
  margin-bottom: 60rpx;
}

.w-200rpx {
  width: 200rpx;
}

.h-200rpx {
  height: 200rpx;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.px-40rpx {
  padding-left: 40rpx;
  padding-right: 40rpx;
}

.mb-30rpx {
  margin-bottom: 30rpx;
}

.w-10rpx {
  width: 10rpx;
}

.h-40rpx {
  height: 40rpx;
}

.bg-black {
  background-color: black;
}

.mr-20rpx {
  margin-right: 20rpx;
}

.text-34rpx {
  font-size: 34rpx;
}

.font-medium {
  font-weight: 500;
}

.text-36rpx {
  font-size: 36rpx;
}

.text-30rpx {
  font-size: 30rpx;
}

.text-gray-500 {
  color: #6b7280;
}

.px-30rpx {
  padding-left: 30rpx;
  padding-right: 30rpx;
}

.p-40rpx {
  padding: 40rpx;
}

.mb-20rpx {
  margin-bottom: 20rpx;
}

.bg-white {
  background-color: white;
}

.rounded-20rpx {
  border-radius: 20rpx;
}

.border {
  border: 1px solid;
}

.border-gray-100 {
  border-color: #f3f4f6;
}

.text-32rpx {
  font-size: 32rpx;
}

.text-gray-700 {
  color: #374151;
}

.bg-blue-500 {
  background-color: #3b82f6;
}

.text-white {
  color: white;
}

.text-28rpx {
  font-size: 28rpx;
}

.px-40rpx {
  padding-left: 40rpx;
  padding-right: 40rpx;
}

.leading-60rpx {
  line-height: 60rpx;
}

.mt-auto {
  margin-top: auto;
}

.mb-10rpx {
  margin-bottom: 10rpx;
}
</style>
